<template>
<div class="Login_S">
  <cube-form :model="model"
              :schema="schema"
              @submit="handleLogin"
              @validate="haneldValidate">
  </cube-form>
  <div class="alert" v-if="showError">
    {{errorMsg}}
  </div>
</div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      errorMsg: '',
      showError: '',
      model: {
        username: '',
        passwd: ''
      },
      schema: {
        fields: [
          {
            type: 'input',
            modelKey: 'username',
            label: '用户名',
            props: {
              placeholder: '请输入用户名'
            },
            rules: {
              // 校验规则
              required: true,
              type: 'string',
              min: 3,
              max: 15,
              usercheck: (val) => {
                return (reslove) => {
                  this.$axios.get('/api/check?username=' + val).then(res => {
                    reslove(res.code === 0)
                  })
                }
              }
            },
            trigger: 'blur',
            messages: {
              required: '用户名不能为空',
              min: '用户名不能少于3个字符',
              max: '用户名不能大于15个字符',
              usercheck: '用户名不存在'
            }
          },
          {
            type: 'input',
            modelKey: 'passwd',
            label: '密码',
            props: {
              type: 'password',
              placeholder: '请输入密码',
              eye: {
                open: true
              }
            },
            rules: {
              required: true
            },
            trigger: 'blur'
          },
          {
            type: 'submit',
            label: '登录'
          }
        ]
      }
    }
  },
  methods: {
    haneldValidate (ret) {
    },
    async handleLogin (e) {
      e.preventDefault()
      const obj = {
        username: this.model.username,
        passwd: this.model.passwd
      }
      const ret = await axios.get('/api/login', { params: obj })
      if (ret.code === 0) {
        localStorage.setItem('token', ret.token)
        this.$store.commit('settoken', ret.token)
      } else {
        this.$notice.info({
          duration: 3,
          content: ret.message || '未知错误'
        })

        // this.showError=true
        // this.errorMsg = ret.message||'未知错误'

        // const toast = this.$createToast({
        //   time:2000,
        //   txt:ret.message||'未知错误',
        //   type:'error'
        // })
        // toast.show()
      }
    }
  }

}
</script>
<style lang="stylus">
</style>
